
const log = console.log.bind(console)
const socket = io()

let UserInfo = {
    username: '',
    avatar: '',
    password: '',
    sex: '',
}

socket.on('connect', () => {
    // 连接成功时触发
    log('连接成功')
})

socket.on('errorMsg', function(data) {
    alert(data.msg)
})

$('#register').on('click', function() {
    // 获取用户信息
    let info = {
        username: $('#register_username').val().trim(),
        password: $('#register_password').val().trim(),
        sex: $('#sex input[name=sex]:checked').val(),
        avatar: $('#register_avatar li.now img').attr('src'),
    }

    let bo = !info.username || !info.password || !info.sex || !info.avatar
    if (bo) {
        alert('请填写完整信息后再提交!')
    } else {
        // 提交用户信息到服务端
        socket.emit('registerUser', info)
    }
})

$('#register_login').on('click', function() {
    // 在注册页登录 跳转到登录页
    jumpToPage('login')
})

socket.on('registerSuccess', function(data) {
    alert('注册成功!')
    UserInfo = { ...data }
    // 跳转登录页面
    jumpToPage('login')
})

$('#foot-logout-btn').on('click', function() {
    // 退出登录
    socket.emit('logout')
    jumpToPage('login')
})

$('#loginBtn').on('click', function() {
    // 获取用户名
    username = $("#username").val().trim()
    password = $('#password').val().trim()
    if (!username) {
        alert('请输入用户名')
        return
    } else if (!password) {
        alert('请输入密码')
        return
    }
    let info = {
        username,
        password,
    }
    socket.emit('login', info)
})

socket.on('loginSuccess', data => {
    UserInfo = { ...data }
    jumpToPage('chat')

    // 设置个人信息 显示在界面上
    $('.avatar_url').attr('src', data.avatar)
    $('.user-list .username').text(data.username)

})

socket.on('loginError', data => {
    let msg = data.msg
    alert(msg)
})

$('#registerBtn').on('click', function() {
    // 跳转注册页
    jumpToPage('register')
})

socket.on('addUser', data => {
    /**
     * 监听添加用户的消息
     * 添加一条系统消息
     */
    let template = JoinOrOutTemplate('join', data)
    $('.box-bd').append(template)
    scrollIntoView()
})

socket.on('userList', data => {
    /**
     * 监听用户列表消息
     * 更新列表之前先清空
     */
    $('.user-list ul').html('')
    data.forEach(item => {
        let template = `
        <li class="user">
            <div class="avatar">
                <img src="${item.avatar}" alt="" />
            </div>
            <div class="name">${item.username}</div>
          </li>
        `
        $('.user-list ul').append(template)
    })

    // 更新用户数
    $('#userCount').text(data.length)
})

socket.on('deleteUser', data => {
    /**
     * 监听用户离开的消息
     * 添加一条系统消息
     */
    let template = JoinOrOutTemplate('leave', data)
    $('.box-bd').append(template)
    scrollIntoView()
})

$('#btn-send').on('click', function() {
    let content = $('#content').html()
    // 清空输入框
    $('#content').html('')
    if (!content) return alert('请输入内容')

    // 发送给服务器
    let info = {
        msg: content,
        username: UserInfo.username,
        avatar: UserInfo.avatar
    }
    socket.emit('sendMessage', info)
})

$("#content").keydown(function(e) {
    /**
     * 触发事件“ctrl+enter”键
     * if (e.ctrlKey && (e.keyCode === 10 || e.keyCode === 13)) {
     */
    if (e.ctrlKey && e.which == 13) {
        console.log("按下ctrl+enter键")
        sendToMsg()
    }
})

socket.on('receiveMessage', data => {
    // 把接收到的消息显示到聊天窗口中
    if (data.username === UserInfo.username) {
        // 自己的消息
        let template = chatMsgTemplate('my', data)
        $('.box-bd').append(template)
    } else {
        // 别人的消息
        let template = chatMsgTemplate('other', data)
        $('.box-bd').append(template)
    }
    scrollIntoView()
})

$('#file').on('change', function() {
    /**
     * 发送图片功能
     * onchange() 表示文件被选择 换文件
     */
    let file = this.files[0]
    // 需要把这个文件发送到服务器, 借助于 H5 新增的 fileReader
    let fr = new FileReader()
    fr.readAsDataURL(file)
    fr.onload = function() {
        socket.emit('sendImage', {
            username: UserInfo.username,
            avatar: UserInfo.avatar,
            img: fr.result
        })
    }
})

socket.on('receiveImage', data => {
    /**
     * 监听图片的聊天信息
     * 把接收到的消息显示到聊天窗口中
     */
    if (data.username === UserInfo.username) {
        // 自己的消息
        let template = chatMsgTemplate('my', data, 'img',)
        $('.box-bd').append(template)
    } else {
        // 别人的消息
        let template = chatMsgTemplate('other', data, 'img',)
        $('.box-bd').append(template)
    }
    // 等待图片加载完成
    $('.box-bd img :last').on('load', function() {
        scrollIntoView()
    })
})

$('.face').on('click', function() {
    /**
     * 显示表情
     */
    $('#content').emoji({
        button: '.face',
        showTab: true,
        animation: 'slide',
        position: 'topRight',
        icons: [
            {
                name: "贴吧表情",
                path: "lib/jquery-emoji/img/tieba/",
                maxNum: 50,
                file: ".jpg",
                placeholder: ":{alias}:",
                alias: {
                    1: "hehe",
                    2: "haha",
                    3: "tushe",
                    4: "a",
                    5: "ku",
                    6: "lu",
                    7: "kaixin",
                    8: "han",
                    9: "lei",
                    10: "heixian",
                    11: "bishi",
                    12: "bugaoxing",
                    13: "zhenbang",
                    14: "qian",
                    15: "yiwen",
                    16: "yinxian",
                    17: "tu",
                    18: "yi",
                    19: "weiqu",
                    20: "huaxin",
                    21: "hu",
                    22: "xiaonian",
                    23: "neng",
                    24: "taikaixin",
                    25: "huaji",
                    26: "mianqiang",
                    27: "kuanghan",
                    28: "guai",
                    29: "shuijiao",
                    30: "jinku",
                    31: "shengqi",
                    32: "jinya",
                    33: "pen",
                    34: "aixin",
                    35: "xinsui",
                    36: "meigui",
                    37: "liwu",
                    38: "caihong",
                    39: "xxyl",
                    40: "taiyang",
                    41: "qianbi",
                    42: "dnegpao",
                    43: "chabei",
                    44: "dangao",
                    45: "yinyue",
                    46: "haha2",
                    47: "shenli",
                    48: "damuzhi",
                    49: "ruo",
                    50: "OK"
                },
                title: {
                    1: "呵呵",
                    2: "哈哈",
                    3: "吐舌",
                    4: "啊",
                    5: "酷",
                    6: "怒",
                    7: "开心",
                    8: "汗",
                    9: "泪",
                    10: "黑线",
                    11: "鄙视",
                    12: "不高兴",
                    13: "真棒",
                    14: "钱",
                    15: "疑问",
                    16: "阴脸",
                    17: "吐",
                    18: "咦",
                    19: "委屈",
                    20: "花心",
                    21: "呼~",
                    22: "笑脸",
                    23: "冷",
                    24: "太开心",
                    25: "滑稽",
                    26: "勉强",
                    27: "狂汗",
                    28: "乖",
                    29: "睡觉",
                    30: "惊哭",
                    31: "生气",
                    32: "惊讶",
                    33: "喷",
                    34: "爱心",
                    35: "心碎",
                    36: "玫瑰",
                    37: "礼物",
                    38: "彩虹",
                    39: "星星月亮",
                    40: "太阳",
                    41: "钱币",
                    42: "灯泡",
                    43: "茶杯",
                    44: "蛋糕",
                    45: "音乐",
                    46: "haha",
                    47: "胜利",
                    48: "大拇指",
                    49: "弱",
                    50: "OK"
                }
            },
            {
                name: "QQ高清",
                path: "lib/jquery-emoji/img/qq/",
                maxNum: 91,
                excludeNums: [41, 45, 54],
                file: ".gif",
                placeholder: "#qq_{alias}#"
            },
            {
                name: "emoji高清",
                path: "lib/jquery-emoji/img/emoji/",
                maxNum: 84,
                file: ".png",
                placeholder: "#emoji_{alias}#"
            }
        ]
    })
})

$('.screen-cut').on('click', function() {
    /**
     * 截图功能
     * 敬请期待
     */
    alert('敬请期待!')
})

$('#register_avatar li').on('click', function() {
    /**
     * 注册功能选择头像
     */
    $(this)
        .addClass('now')
        .siblings()
        .removeClass('now')
})

const jumpToPage = (page) => {
    let pageArr = [
        'login_box',
        'register_box',
        'container',
    ]
    const pageMap = {
        login: 'login_box',
        register: 'register_box',
        chat: 'container',
    }
    let element = pageMap[page]
    let eleStr = `.${element}`
    $(eleStr).fadeIn()
    let pageIndex = pageArr.findIndex(item => item === element)
    if (pageIndex > -1) {
        pageArr.splice(pageIndex, 1)
    }
    pageArr.forEach(item => {
        let ele = `.${item}`
        $(ele).fadeOut()
    })

}

const sendToMsg = () => {
    let content = $('#content').html()
    // 清空输入框
    $('#content').html('')
    if (!content) return alert('请输入内容')

    // 发送给服务器
    let info = {
        msg: content,
        username: UserInfo.username,
        avatar: UserInfo.avatar
    }
    socket.emit('sendMessage', info)
}

const scrollIntoView = () => {
    /**
     * 当前元素（最近一条消息）底部滚动到可视区
     * 找到 .box-bd 最后一个子元素
     */
    $('.box-bd').children(':last').get(0).scrollIntoView(false)
}

const JoinOrOutTemplate = (action, data) => {
    // 加入或离开房间
    const actionMap = {
        'leave': '离开',
        'join': '加入',
    }
    let template = `
    <div class="system">
        <p class="message_system">
            <span class="content">"${data.username}"${actionMap[action]}了群聊</span>
        </p>
    </div>
    `
    return template
}

const chatMsgTemplate = (role = 'my', data, type = 'text',) => {
    // 聊天的消息模板
    let str1 = role === 'other' ? `<div class="nickname">${data.username}</div>` : ''
    let str2 = type === 'img' ? `<img src="${data.img}"/>` : data.msg

    let template = `
        <div class="message-box">
        <div class="${role} message">
            <img class="avatar" src="${data.avatar}" alt="" />
            <div class="content">
            ${str1}
            <div class="bubble">
                <div class="bubble_cont">
                    ${str2}
                </div>
            </div>
            </div>
        </div>
        </div>
    `
    return template
}
